package com.kly.smartbi.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.kly.smartbi.constant.UserContext;
import com.kly.smartbi.model.dto.user.UserDto;
import com.kly.smartbi.model.entity.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.kly.smartbi.constant.UserConstant.USER_INFO_KEY;
import static com.kly.smartbi.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author admin
 * @date 2025/3/29
 */
public class LoginInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //     跳过静态方法
        if(request.getMethod().equals("OPTIONS")) {
            return true;
        }
    //     只存储用户信息
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if(userObj != null) {
            User user = (User) userObj;
            UserContext.saveUser(BeanUtil.copyProperties(user, UserDto.class));
        }
        // 获取用户信息
        // 获取token
        String token = request.getHeader("token");
        String key = USER_INFO_KEY + token;
        String userInfo = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(userInfo)) {
            User bean = JSONUtil.toBean(userInfo, User.class);
            System.out.println(bean);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
